package net.cruciblesoftware.ghostspacekillah;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import java.util.Random;

class Bullet extends FieldActor {
    public static final int STATE_INACTIVE = 0;
    public static final int STATE_ACTIVE = 1;

    private float maxVel;
    private float velX, velY;

    public Bullet(float x, float y, int rot) {
        super(FieldActor.TYPE_BULLET);
        posX = x;
        posY = y;
        rotation = rot * 2;
        maxVel = Settings.getPercent("bullet_max_vel");
        velX = (float)(Math.sin(Math.toRadians(rot)) * maxVel * SceneView.width);
        velY = (float)(Math.cos(Math.toRadians(rot)) * maxVel * SceneView.height);

        setState(STATE_ACTIVE);
        setImage(Assets.getBitmap(type));
        frameStepTime = Settings.getPercent("bullet_frame_step_time");
    }


    public void update(float elapsed) { 
        if(state == STATE_ACTIVE) {
            posX += velX * elapsed;
            posY -= velY * elapsed;
            frameTime += elapsed;
        }
        if(posX < 0.0f || posX > SceneView.width || 
           posY < 0.0f || posY > SceneView.height) {
            state = STATE_INACTIVE;
        }
    }


    public void draw(Canvas c) { 
        if(state == Bullet.STATE_INACTIVE)
            return;

        if(frameTime > frameStepTime) {
            frameTime -= frameStepTime;
            currentFrame++;
            if(currentFrame >= nFrames)
                currentFrame = 0;
            src.left = currentFrame * imgWidth;
            src.right = (currentFrame+1) * imgWidth;
        }
        int w_2 = imgWidth / 2;
        int h_2 = imgHeight / 2;
        dest.left = (int)(posX - w_2);
        dest.top = (int)(posY - h_2);
        dest.right = (int)(posX + w_2);
        dest.bottom = (int)(posY + h_2);
        c.save();
        c.rotate((float)rotation, posX, posY);
        c.drawBitmap(img, src, dest, null);
        c.restore();
    }


    public void setState(int newState) {
        if(newState == Bullet.STATE_INACTIVE ||
           newState == Bullet.STATE_ACTIVE)
            state = newState;
    }


    /* Logging functions */
    private void logi(String msg) {
        android.util.Log.i(this.getClass().getName(), msg);
    }
    private void logw(String msg) {
        android.util.Log.w(this.getClass().getName(), msg);
    }
    private void loge(String msg) {
        android.util.Log.e(this.getClass().getName(), msg);
    }
}
